<?php
include_once("conn.php");

$id=$_REQUEST['id'];
$pass=$_REQUEST['pass'];
$type=$_REQUEST['type'];

checkCount();
$sql=setSQL($type,$id);

$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if ($row[2]==md5($pass)){
	setcookie( "type", "$type", time()+3600);
	setcookie( "id", "$id", time()+3600);
	clearCount();
	echo "Login Successful."."<br/>";
	echo "<a href=\"left.php\" target=\"leftFrame\">Continue.</a>";
}
else {
	echo "Wrong Password";
}
mysql_free_result($result);
mysql_close($conn);

function checkCount(){
	$cookie=$_COOKIE['count'];
	if ($cookie==null){
		setCount(1);
	}
	else if($cookie<3){
		setCount($cookie+1);
	}
	else{
		echo "<script language=\"javascript\">";
		echo "alert(\"Have Login 3 Tims, wait for one minute.\")";
		echo "</script>";
	}
}

function setCount($haveLogedInTimes){
	setcookie( "count", "$haveLogedInTimes", time()+60);
}

function clearCount(){
	setcookie( "count", "", time()-1);
}

function setSQL($type,$id){
	switch ($type) {
		case 0:
			$sql = "SELECT * FROM student WHERE `id` = '$id'";
			break;
		case 1:
			$sql = "SELECT * FROM teacher WHERE `id` = '$id'";
			break;
		case 2:
			$sql = "SELECT * FROM admin WHERE `id` = '$id'";
			break;
	}
	return $sql;
}
?>